package com.luoyx.vjsb.common.util;

import cn.hutool.json.JSONUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiang.github.io</p>
 * @since 2020/3/20 15:41
 */
@Data
@Slf4j
@ApiModel(description = "返回封装")
public class AjaxResult<T> {

    /**
     * 状态
     */
    @ApiModelProperty(value = "状态码", example = "0")
    private Integer status;
    /**
     * 信息
     */
    @ApiModelProperty(value = "信息")
    private String message;
    /**
     * 数据
     */
    @ApiModelProperty(value = "返回数据")
    private T data;

    private AjaxResult(String message, Integer status, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    public static <T> AjaxResult<T> success() {
        return new AjaxResult<>("操作成功", 0, null);
    }
    public static <T> AjaxResult<T> success(T data) {
        return new AjaxResult<>("操作成功", 0, data);
    }
    public static <T> AjaxResult<T> success(T data, String message) {
        return new AjaxResult<>(message,0, data);
    }
    public static <T> AjaxResult<T> success(String message, Integer status, T data) {
        return new AjaxResult<>(message, status, data);
    }

    public static <T> AjaxResult<T> error() {
        return new AjaxResult<>("操作失败", -1, null);
    }
    public static <T> AjaxResult<T> error(String message) {
        return new AjaxResult<>(message, -1, null);
    }
    public static <T> AjaxResult<T> error(Integer status) {
        return new AjaxResult<>("操作失败", status, null);
    }

    /**
     *  使用response输出JSON
     * @param response 1
     * @param ajaxResult 1
     */
    public static <T> void out(HttpServletResponse response, AjaxResult<T> ajaxResult){

        ServletOutputStream out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            out = response.getOutputStream();
            out.write(JSONUtil.toJsonStr(ajaxResult).getBytes());
        } catch (Exception e) {
            log.error(e + "输出JSON出错");
        } finally{
            if(out!=null){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
